package cas.ihep.alluxio.impl;

import alluxio.AlluxioURI;
import alluxio.client.file.URIStatus;
import cas.ihep.alluxio.AlluxioBlock;
import cas.ihep.alluxio.AlluxioFile;
import cas.ihep.alluxio.AlluxioSystem;
import com.google.common.io.Closer;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public abstract class AlluxioBaseFile implements AlluxioFile{
    AlluxioBaseSystem mSys;
    AlluxioURI mUri;
    URIStatus mStatus;
    Map<Long,AlluxioBaseBlock> mBlocks;
    Closer mCloser;
    protected boolean mClosed;

    long mFileLength;
    long mBlockSize;

    AlluxioBaseFile(AlluxioBaseSystem sys, AlluxioURI path){
        mSys=sys;
        mUri=path;
        mStatus=null;
        mBlocks=new HashMap<>();
        mCloser=Closer.create();
        mClosed=false;
    }

    public void close() throws IOException {
        if(!mClosed){
            try {
                mCloser.close();
            }finally {
                mClosed=true;
            }
        }
    }

    public long getLength(){
        return mFileLength;
    }

    long getBlockSize(long pos){
        long lastBlockSize = mFileLength % mBlockSize;
        if (mFileLength - pos > lastBlockSize) {
            return mBlockSize;
        } else {
            return lastBlockSize;
        }
    }

    public abstract AlluxioFile open()throws IOException;
    public abstract AlluxioBlock getBlock(int idx)throws IOException;
    public abstract AlluxioBlock nextBlock()throws IOException;
    public abstract boolean canRead();
    public abstract boolean canWrite();

    public final AlluxioSystem getSystem(){
        return mSys;
    }
}
